package com.dgz.friend.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.dgz.common.core.constants.Constants;
import com.dgz.common.core.domain.R;
import com.dgz.common.core.domain.TableDataInfo;
import com.dgz.common.core.uitls.ThreadLocalUtil;
import com.dgz.friend.domain.exam.dto.ExamQueryDto;
import com.dgz.friend.domain.exam.dto.ExamRankDTO;
import com.dgz.friend.domain.exam.vo.ExamRankVO;
import com.dgz.friend.domain.exam.vo.ExamVO;
import com.dgz.friend.domain.user.vo.UserVO;
import com.dgz.friend.manager.ExamCacheManager;
import com.dgz.friend.manager.UserCacheManager;
import com.dgz.friend.mapper.exam.ExamMapper;
import com.dgz.friend.mapper.user.UserExamMapper;
import com.dgz.friend.service.exam.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/05/07/14:04
 * @Description:
 */
@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;


    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private UserCacheManager userCacheManager;


    @Override
    public List<ExamVO> list(ExamQueryDto examQueryDto) {
        PageHelper.startPage(examQueryDto.getPageNum(), examQueryDto.getPageSize());
        return examMapper.selectExamList(examQueryDto);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDto examQueryDto) {
        // 从redis中获取 列表数据数量
        Long total = examCacheManager.getListSize(examQueryDto.getType(),null);
        List<ExamVO> examVOList;
        if(total == null || total <= 0) {
            examVOList = list(examQueryDto);
            // 刷新缓存
            examCacheManager.refreshCache(examQueryDto.getType(),null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            // 从redis中获取 列表数据
            examVOList = examCacheManager.getExamVOList(examQueryDto,null);
            total = examCacheManager.getListSize(examQueryDto.getType(),null);
        }
        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamVoList(examVOList);
        return TableDataInfo.success(examVOList,total);
    }

    @Override
    public String getFirstQuestion(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if(listSize == null || listSize == 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
        return examCacheManager.getFirstQuestion(examId);
    }

    @Override
    public String preQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.preQuestion(examId, questionId).toString();
    }

    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId, questionId).toString();
    }

    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examRankDTO.getPageNum(), examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
        }
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList, total);
    }

    private void assembleExamVoList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if(CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }

    /**
     * 检查缓存，如果缓存中没有数据，则刷新缓存
     * @param examId
     */
    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }
    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }
}
